"""
Test runner for TIR - provides manual testing capabilities
"""

import os
import sys
from pathlib import Path

# Add the parent directory to Python path so we can import tir
sys.path.insert(0, str(Path(__file__).parent.parent))

from tir.cli import TIRAnalyzer


def run_manual_tests():
    """Run manual tests on sample files."""
    print("🧪 TIR Manual Testing Suite")
    print("=" * 50)
    
    test_files_dir = Path(__file__).parent / 'test_samples'
    
    # Test cases: (file, line, column, expected_symbol, description)
    test_cases = [
        ('simple_templates.cpp', 12, 20, 'int_vector', 'Simple std::vector<int>'),
        ('simple_templates.cpp', 15, 20, 'matrix', 'Nested std::vector<std::vector<double>>'),
        ('simple_templates.cpp', 18, 20, 'string_to_int', 'std::map<std::string, int>'),
        ('simple_templates.cpp', 21, 20, 'complex_map', 'Complex nested map'),
        ('simple_templates.cpp', 24, 20, 'auto_vector', 'Auto variable with template'),
        ('complex_templates.cpp', 34, 20, 'deeply_nested', 'Deeply nested templates'),
        ('complex_templates.cpp', 37, 20, 'custom_template', 'Custom template with namespace'),
        ('complex_templates.cpp', 40, 20, 'aliased_map', 'Template alias usage'),
        ('modern_cpp.cpp', 28, 20, 'optional_vector', 'C++17 std::optional'),
        ('modern_cpp.cpp', 31, 20, 'variant_value', 'C++17 std::variant'),
    ]
    
    analyzer = TIRAnalyzer()
    
    passed = 0
    failed = 0
    skipped = 0
    
    for file_name, line, column, symbol, description in test_cases:
        print(f"\n📋 Test: {description}")
        print(f"   File: {file_name}, Line: {line}, Column: {column}")
        print("-" * 40)
        
        file_path = test_files_dir / file_name
        
        if not file_path.exists():
            print(f"⚠️  SKIP: Test file not found: {file_path}")
            skipped += 1
            continue
        
        try:
            # Test position-based analysis
            result = analyzer.analyze_symbol_at_position(
                str(file_path), line, column, "basic"
            )
            
            if result.startswith("❌") or result.startswith("⚠️"):
                print(f"❌ FAIL: {description}")
                print(f"   Result: {result[:100]}...")
                failed += 1
            else:
                print(f"✅ PASS: {description}")
                # Show first few lines of result
                lines = result.split('\n')
                for line in lines[:5]:
                    print(f"   {line}")
                if len(lines) > 5:
                    print("   ...")
                passed += 1
                
            # Also test name-based analysis if we have a symbol name
            if symbol and not result.startswith("❌") and not result.startswith("⚠️"):
                name_result = analyzer.analyze_symbol_by_name(
                    str(file_path), symbol, "basic"
                )
                
                if name_result.startswith("❌") or name_result.startswith("⚠️"):
                    print(f"⚠️  Name-based analysis failed for {symbol}")
                else:
                    print(f"✅ Name-based analysis also succeeded for {symbol}")
        
        except Exception as e:
            print(f"💥 ERROR: {description}")
            print(f"   Exception: {e}")
            failed += 1
    
    print("\n" + "=" * 50)
    print("📊 Test Summary:")
    print(f"   ✅ Passed: {passed}")
    print(f"   ❌ Failed: {failed}")
    print(f"   ⚠️  Skipped: {skipped}")
    print(f"   📝 Total: {passed + failed + skipped}")
    
    if failed == 0:
        print("\n🎉 All tests passed!")
        return True
    else:
        print(f"\n😞 {failed} tests failed")
        return False


def test_specific_case():
    """Test a specific case for debugging."""
    print("🎯 Testing specific case")
    
    test_files_dir = Path(__file__).parent / 'test_samples'
    file_path = test_files_dir / 'simple_templates.cpp'
    
    if not file_path.exists():
        print(f"Test file not found: {file_path}")
        return
    
    analyzer = TIRAnalyzer()
    
    try:
        # Test different output formats
        for fmt in ['basic', 'detailed', 'json']:
            print(f"\n--- {fmt.upper()} FORMAT ---")
            result = analyzer.analyze_symbol_at_position(
                str(file_path), 12, 20, fmt
            )
            print(result)
            print()
    
    except Exception as e:
        print(f"Error: {e}")
        import traceback
        traceback.print_exc()


def main():
    """Main test runner."""
    if len(sys.argv) > 1 and sys.argv[1] == 'specific':
        test_specific_case()
    else:
        run_manual_tests()


if __name__ == '__main__':
    main()